package cn.smbms.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.smbms.pojo.User;
import cn.smbms.service.UserService;
import cn.smbms.tools.Constants;

@Controller
public class LoginController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login.html")
	public String login(){
		return "login";
	}
	
	
	@RequestMapping("/doLogin.html")
	public String doLogin(String userCode,String userPassword,HttpServletRequest request){
		
		User user = userService.login(userCode, userPassword);
		
		if (null != user) {// 登录成功
			// 放入session
			request.getSession().setAttribute(Constants.USER_SESSION, user);
			// 页面跳转（frame.jsp）
			return "redirect:/main.html";
		} else {
			// 页面跳转（login.jsp）带出提示信息--转发
			request.setAttribute("error", "用户名或密码不正确");
			return "login";
		}
		
	}
	
	@RequestMapping("/main.html")
	public String main(){
		return "frame";
	}
	
	
	@RequestMapping(value="/exlogin.html",method=RequestMethod.GET)
	public String exLogin(@RequestParam String userCode,@RequestParam String userPassword){
		
		//调用service方法，进行用户匹配
		User user = userService.login(userCode,userPassword);
		if(null == user){//登录失败
			throw new RuntimeException("用户名或者密码不正确！");
		}
		return "redirect:/main.html";
	}
	
//	@ExceptionHandler(value={RuntimeException.class})
//	public String handlerException(RuntimeException e,HttpServletRequest req){
//		req.setAttribute("e", e);
//		return "error";
//	}
}
